<?php

class Application_Model_PageMapper
{
    protected $_dbTable;

    public function setDbTable($dbTable)
    {
        if (is_string($dbTable)) {
            $dbTable = new $dbTable();
        }
        if (!$dbTable instanceof Zend_Db_Table_Abstract) {
            throw new Exception('Invalid table data gateway provided');
        }
        $this->_dbTable = $dbTable;
        return $this;
    }

    public function getDbTable()
    {
        if (null === $this->_dbTable) {
            $this->setDbTable('Application_Model_DbTable_Page');
        }
        return $this->_dbTable;
    }

    public function findByKey($key, Application_Model_Page $page)
    {

        $language = Zend_Registry::get('language');
        $db       = Zend_Registry::get('db');

        if ($db && $language->getId() > 0) {
            $select = $db->select()->from(array('p' => 'page'));
            $select->join(array('pl' => 'page_local'), 'pl.page_id = p.id');
            $select->where('p.key = ?',          $key);
            $select->where('pl.language_id = ?', $language->getId());
            $stmt = $db->query($select);
            $result = $stmt->fetch();

            if (!empty($result) && is_array($result)) {
                if (!empty($result['id'])) {
                    $page->setId($result['id']);
                }
                if (!empty($result['key'])) {
                    $page->setKey($result['key']);
                }
                if (!empty($result['enabled'])) {
                    $page->setEnabled($result['enabled']);
                }
                if (!empty($result['title'])) {
                    $page->setTitle($result['title']);
                }
                if (!empty($result['content'])) {
                    $page->setContent($result['content']);
                }
                if (!empty($result['meta_desc'])) {
                    $page->setMetaDescription($result['meta_desc']);
                }
                if (!empty($result['meta_keys'])) {
                    $page->setMetaKeywords($result['meta_keys']);
                }
            }
        }

        return $page;
    }
}